/*
 * Change Logs:
 * Date           Author       Notes
 * 2020-10-30     chenbin      small crond the first version
 */
#include "board.h"
#include "stdio.h"
#include "string.h"

#include "small_crond.h"

#define sleep rt_thread_mdelay

//static small_cron_t cron;

const char crond_text[] = "\
*/5 9-19 * * * echo rt-thread\n\
0 9-19 * * * date\n";

void crond_task(void *par)
{
	small_cron_t *cron = par;
	struct tm stm;
	time_t t1,t2;
	uint32_t dt;
	uint32_t sleep_time;
	sleep(30000);
	t1 = 0;
	t2 = 0;
	t1 = t2 = time(NULL); // now time
	
	localtime_r(&t1,&stm);
	rt_kprintf("crond run: %d %d %d %d %d %d\n",stm.tm_year+1900,stm.tm_mon+1,stm.tm_mday,stm.tm_hour,stm.tm_min,stm.tm_sec);
	while(1)
	{
		t1 = t2;
		t2 = time(NULL); // now time
		sleep_time = 60*1000 - (t2%60)*1000; // alignment
		sleep(sleep_time);
		t2 = time(NULL); // now time
		dt = t2 - t1;
		if((0<dt)&&(dt<120))
		{
			cron_jobs_check(cron,t1,t2);
			cron_jobs_run(cron);
		}else
		{
			rt_kprintf("crond time diff %d\n",dt);
		}
	}
}

int crond_run(char *cmd, uint32_t length)
{
	int rc = 0;
	struct tm stm;
	time_t t1 = time(NULL);
	localtime_r(&t1,&stm);
	rt_kprintf("\ncrond at %d-%d-%d %02d:%02d:%02d ",stm.tm_year+1900,stm.tm_mon+1,stm.tm_mday,stm.tm_hour,stm.tm_min,stm.tm_sec);
	rc = run_cmd(cmd,length);
	rt_thread_mdelay(500);
	return rc;
}

int crond_init(small_cron_t *cron)
{
  rt_thread_t tid;
	cron->run = crond_run;
	
	if(cron->line_max == 0)
	{
		static uint8_t line_array[16*sizeof(struct cron_line)];
		
		cron->line_max = 16;
		cron->line_used = 0;
		cron->line_array = (void*)line_array;
	}
	
	cron_text_load(cron,crond_text,rt_strlen(crond_text));
	
	tid = rt_thread_create("crond", crond_task,(void *)cron,4096, 16, 10);
	if (tid)
	{
		rt_thread_startup(tid);
	}
	return 0;
}
//static int crond(uint8_t argc, char **argv)
//{
//	static uint8_t is_run = 0;
//	if(is_run == 0)
//	{
//		is_run = 1;
//		crond_init(&cron);
//	}else
//	{
//		rt_kprintf("crond is runing\n");
//	}
//	return 0;
//}
//MSH_CMD_EXPORT(crond, crond);

